<template>
  <yt-page title="整改复查任务">
    <yt-form>
      <yt-card title="基本信息">
        <yt-cell label="文书编号" :value="form.document_num"></yt-cell>
        <yt-cell label="复查时间">
          <yt-cell-time v-model="form.review_date"></yt-cell-time>
        </yt-cell>
        <yt-cell label="复查人员">
          <yt-cell-select v-model="form.review_person" :max="3" :list="userList" label="DisplayName" val="id"></yt-cell-select>
        </yt-cell>
        <yt-textarea class="input" border="none" title="复查情况" type="row" v-model="form.review_remarks"></yt-textarea>
      </yt-card>
      <yt-card title="整改清单">
        <yt-cellSwipe :data="index" :items="items" v-for="(item, index) in records" :key="index">
          <div class="row">
            <span class="row-circle" :class="getClass(item)"></span>
            <div class="row-content">{{ item.danger_desc }}</div>
          </div>
        </yt-cellSwipe>
      </yt-card>
      <yt-btn v-if="form.state === 0" slot="btn" :loading="onSubmit" theme="blue" edge>保存</yt-btn>
      <yt-btn-group v-else slot="btn" :shadow="false" edge>
        <yt-btn theme="white" :loading="onSubmit" :loadingOption="{color: '#46baff'}">保存</yt-btn>
        <yt-btn theme="white" :loading="onPreview" :loadingOption="{color: '#46baff'}">预览文书</yt-btn>
      </yt-btn-group>
    </yt-form>
  </yt-page>
</template>

<script>
import { PointerToString, BuildPointer } from '@/common/utils/index.js'
import { commonApi } from '@/common/api/commonApi.js'
import { bridge } from '@/common/plugin/index.js'

export default {
  data() {
    return {
      form: {},
      userList: [],
      records: [],
      items: [
        {
          type: 'red',
          text: '未整改',
          click: index => this.updateState(index, 2)
        },
        {
          type: 'yellow',
          text: '延期',
          click: index => this.updateState(index, 3)
        },
        {
          type: 'green',
          text: '已整改',
          click: index => this.updateState(index, 1)
        }
      ]
    }
  },
  activated() {
    if (!this.$router.$isBack) {
      this.init()
      this.fetchData()
      this.fetchRecord()
    }
  },
  methods: {
    updateState(index, state) {
      let obj = { ...this.records[index], result: state }
      this.records.splice(index, 1, obj)
    },
    getClass(item) {
      switch (item.result) {
        case '1':
        case 1:
          return 'is-complete'
        case '2':
        case 2:
          return 'is-uncomplete'
        case '3':
        case 3:
          return 'is-delay'
        default:
          return 'is-default'
      }
    },
    async onSubmit(loaded) {
      try {
        let form = BuildPointer(this.form, {
          review_person: 'aj_organization_personnel'
        })
        let objects = this.records.reduce((results, item) => {
          if (item.result !== null && item.result !== undefined) {
            let obj = commonApi.createInstance('law_record_danger', {
              id: item.id,
              result: item.result + ''
            })
            results.push(obj)
          }
          return results
        }, [])
        if (form.state !== 1) {
          form.state = 1
        }
        let obj = objects.find(v => v.attributes.result === '3')
        await commonApi.save('law_plan', {
          id: this.$route.query.id,
          state: obj ? 7 : 6
        })
        let p = [commonApi.save('law_review', form), commonApi.saveAll(objects)]
        await Promise.all(p)
        this.$router.$back()
        this.$Toast('保存成功!', 'success')
      } catch (e) {
        this.$Toast('保存失败!', 'error')
      }
      loaded()
    },
    async init() {
      this.review = this.$route.query.review
      let form = await commonApi.searchById('law_review', this.review)
      this.form = PointerToString(form, ['review_person:array'])
      if (this.form.document_num) return
      let { D0004 } = await commonApi.runCloud('lawGetDocumentNum', {
        year: new Date().getFullYear()
      })
      this.form = { ...this.form, document_num: D0004 }
    },
    async fetchData() {
      this.userList = await commonApi.search('aj_organization_personnel', {
        include: ['OrganizationIds'],
        matchesQuery: {
          OrganizationIds: commonApi.createQueryIncludeOptions(
            'sys_organizations',
            {
              equalTo: {
                Name: '安监局执法'
              }
            }
          )
        }
      })
    },
    async fetchRecord() {
      let record = this.$route.query.record
      this.records = await commonApi.search('law_record_danger', {
        equalTo: { record_id: record },
        include: ['score']
      })
      this.selectList = this.records.filter(v => v.state)
    },
    async onPreview(loaded) {
      try {
        let word = await commonApi.runCloud('officeCopy', {
          code: 'D0004',
          data: this.$route.query.id
        })
        let { url } = await commonApi.runCloud('WordToPdf', { word })
        if (!url) {
          this.$Toast('文件转换失败，请尝试重新预览！', 'error')
          loaded()
          return
        }
        bridge.PreviewPdf({ title: '文件标题', url: url })
      } catch (e) {}
      loaded()
    }
  }
}
</script>

<style scoped lang="stylus">
.input
  >>> .yt-textarea-title
    border none

.row
  display flex
  align-items center
  color #666
  line-height 30px
  font-size 14px

  &-circle
    display inline-block
    margin 0 10px
    width 14px
    height 14px
    border-radius 50%

    &.is-default
      background-color #ddd

    &.is-complete
      background-color #29f090

    &.is-uncomplete
      background-color #ff0000

    &.is-delay
      background-color #ff9d01

  &-content
    flex 1
</style>
